<template>
  <div class="after-care-container">
    <!-- 顶部区域 -->
    <div class="header">
      <div class="header-content">
        <div class="icon-wrapper">
          <i class="ivu-icon ivu-icon-md-heart custom-icon"></i>
        </div>
        <h2 class="welcome-text">诊后关心服务</h2>
        <p class="sub-text">我们将持续关注您的康复情况，随时为您提供帮助</p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <Row :gutter="20">
        <!-- 左侧就诊记录列表 -->
        <Col span="8">
          <Card class="visit-history">
            <div slot="title">
              <Icon type="md-list"></Icon>
              就诊记录
            </div>
            <div class="visit-list">
              <div v-for="(visit, index) in visitHistory" 
                   :key="index" 
                   class="visit-item"
                   :class="{ active: currentVisit && currentVisit.id === visit.id }"
                   @click="selectVisit(visit)">
                <div class="visit-info">
                  <div class="visit-date">{{ formatDateTime(visit.visitDate) }}</div>
                  <div class="visit-department">{{ visit.department }}</div>
                </div>
                <div class="visit-doctor">
                  <Icon type="md-person"></Icon>
                  {{ visit.doctorName }}
                </div>
                <div class="visit-diagnosis">
                  <p><strong>诊断：</strong>{{ visit.diagnosis }}</p>
                  <p><strong>主诉：</strong>{{ visit.chiefComplaint || '暂无主诉信息' }}</p>
                </div>
              </div>
            </div>
          </Card>
        </Col>

        <!-- 右侧用药提醒和康复建议区域 -->
        <Col span="16">
          <Card class="follow-up-card">
            <Tabs v-model="activeTab">
              <!-- 用药提醒标签页 -->
              <TabPane label="用药提醒" name="medication">
                <div v-if="medications.length === 0" class="empty-tip">
                  <Icon type="ios-information-circle-outline" size="48" />
                  <p>暂无用药提醒信息</p>
                </div>
                <div v-else class="medication-list">
                  <Card v-for="(med, index) in medications" 
                        :key="index"
                        class="medication-item">
                    <div class="med-header">
                      <span class="med-name">{{ med.medicineName }}</span>
                      <Tag :color="getMedicationStatus(med)">
                        {{ getMedicationStatusText(med) }}
                      </Tag>
                    </div>
                    <div class="med-details">
                      <p><Icon type="md-time"></Icon> 用法：{{ med.usageMethod }}</p>
                      <p><Icon type="md-calendar"></Icon> 频次：{{ med.frequency }}</p>
                      <p><Icon type="md-information-circle"></Icon> 用药天数：{{ med.days }}天</p>
                      <p><Icon type="md-cube"></Icon> 单次剂量：{{ med.singleDose }}{{ med.unit }}</p>
                      <p><Icon type="md-calculator"></Icon> 总剂量：{{ med.totalDose }}{{ med.unit }}</p>
                      <p v-if="med.notes"><Icon type="md-document"></Icon> 备注：{{ med.notes }}</p>
                    </div>
                  </Card>
                </div>
              </TabPane>

              <!-- 康复建议标签页 -->
              <TabPane label="康复建议" name="advice">
                <div class="advice-content">
                  <Alert v-if="currentVisit" type="info" show-icon>
                    <Icon slot="icon" type="md-information-circle"></Icon>
                    <h3 slot="desc">
                      以下建议基于您 {{ formatDateTime(currentVisit.visitDate) }} 的就诊记录
                    </h3>
                  </Alert>
                  <div class="advice-list">
                    <Card v-for="(advice, index) in recoveryAdvice" 
                          :key="index"
                          class="advice-item">
                      <div class="advice-title">
                        <Icon :type="advice.icon"></Icon>
                        {{ advice.title }}
                      </div>
                      <div class="advice-detail">{{ advice.content }}</div>
                    </Card>
                  </div>
                </div>
              </TabPane>
            </Tabs>
          </Card>
        </Col>
      </Row>
    </div>
  </div>
</template>

<script>
import { getPrescriptionDetails } from '@/api/prescription'
import { getRecoveryAdviceList } from '@/api/recoveryAdvice'
import { getPatientHistory } from '@/api/medical-dashboard'
import Cookies from 'js-cookie'

export default {
  name: 'AfterCare',
  data() {
    return {
      activeTab: 'medication',
      currentVisit: null,
      visitHistory: [],
      medications: [],
      recoveryAdvice: [],
      userId: null,
      patientId: null
    }
  },
  methods: {
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    getUserInfo() {
      const userInfoStr = Cookies.get('userInfo');
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr);
          this.userId = userInfo.id;
          // 如果是患者角色，patientId就是userId
          this.patientId = userInfo.id;
          return true;
        } catch (error) {
          console.error('解析用户信息失败:', error);
          return false;
        }
      }
      return false;
    },
    async loadVisitHistory() {
      try {
        if (!this.getUserInfo()) {
          this.$Message.error('获取用户信息失败，请重新登录');
          return;
        }
        
        console.log('开始获取就诊记录, patientId:', this.patientId, 'userId:', this.userId);
        const response = await getPatientHistory(this.userId, this.patientId);
        console.log('【getPatientHistory 响应】', response);
        
        const history = response.result || response.data || [];
        this.visitHistory = history;
        
        // 如果有就诊记录，自动选择第一条
        if (this.visitHistory && this.visitHistory.length > 0) {
          await this.selectVisit(this.visitHistory[0]);
        } else {
          console.warn('没有找到就诊记录');
          this.$Message.info('暂无就诊记录');
        }
      } catch (error) {
        console.error('获取就诊记录失败:', error);
        this.$Message.error('获取就诊记录失败');
      }
    },
    async selectVisit(visit) {
      console.log('选择就诊记录:', visit);
      this.currentVisit = visit;
      await this.loadMedications();
      await this.loadRecoveryAdvice();
    },
    async loadMedications() {
      if (!this.currentVisit) {
        console.warn('没有选择就诊记录');
        this.medications = [];
        return;
      }

      const recordId = this.currentVisit.medicalRecordId || this.currentVisit.id;
      console.log('加载处方详情, 记录ID:', recordId);

      try {
        const response = await getPrescriptionDetails(recordId);
        console.log('处方详情响应:', response);
        
        // 处理不同的响应格式
        let prescriptionData = response.result || response.data || response;
        
        if (Array.isArray(prescriptionData)) {
          this.medications = prescriptionData.map(med => ({
            ...med,
            validityEndTime: med.validityEndTime || this.calculateValidityEndTime(med)
          }));
          console.log('处理后的处方数据:', this.medications);
        } else {
          console.warn('处方数据格式不正确:', prescriptionData);
          this.$Message.warning('未找到处方信息');
          this.medications = [];
        }
      } catch (error) {
        console.error('加载用药提醒失败:', error);
        this.$Message.error(error.message || '加载用药提醒失败');
        this.medications = [];
      }
    },
    calculateValidityEndTime(med) {
      if (med.startTime && med.days) {
        const startDate = new Date(med.startTime);
        return new Date(startDate.setDate(startDate.getDate() + med.days));
      }
      return null;
    },
    async loadRecoveryAdvice() {
      if (!this.currentVisit) {
        console.warn('没有选择就诊记录');
        this.recoveryAdvice = [];
        return;
      }

      const recordId = this.currentVisit.medicalRecordId || this.currentVisit.id;
      console.log('加载康复建议, 记录ID:', recordId);

      try {
        // 直接从就诊记录中获取康复建议
        if (this.currentVisit.adviceType && this.currentVisit.adviceContent) {
          this.recoveryAdvice = [{
            adviceType: this.currentVisit.adviceType,
            title: this.currentVisit.adviceTitle || this.getAdviceTypeText(this.currentVisit.adviceType),
            content: this.currentVisit.adviceContent,
            icon: this.getAdviceIcon(this.currentVisit.adviceType)
          }];
          console.log('处理后的康复建议:', this.recoveryAdvice);
        } else {
          console.warn('未找到康复建议');
          this.$Message.warning('未找到康复建议');
          this.recoveryAdvice = [];
        }
      } catch (error) {
        console.error('加载康复建议失败:', error);
        this.$Message.error(error.message || '加载康复建议失败');
        this.recoveryAdvice = [];
      }
    },
    getAdviceTypeText(type) {
      const typeMap = {
        'DIET': '饮食建议',
        'EXERCISE': '运动建议',
        'LIFESTYLE': '生活习惯建议'
      };
      return typeMap[type] || '其他建议';
    },
    getAdviceIcon(type) {
      const iconMap = {
        'DIET': 'md-nutrition',
        'EXERCISE': 'md-walk',
        'LIFESTYLE': 'md-alarm'
      };
      return iconMap[type] || 'md-information-circle';
    },
    getMedicationStatus(med) {
      const now = new Date();
      const endTime = new Date(med.validityEndTime);
      if (now > endTime) {
        return 'default'; // 已过期
      }
      return 'success'; // 进行中
    },
    getMedicationStatusText(med) {
      return this.getMedicationStatus(med) === 'success' ? '进行中' : '已过期';
    }
  },
  async created() {
    await this.loadVisitHistory();
  }
}
</script>

<style scoped>
.after-care-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.icon-wrapper {
  width: 64px;
  height: 64px;
  background: linear-gradient(135deg, #ff4d4f, #cf1322);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(207, 19, 34, 0.2);
}

.custom-icon {
  color: white;
  font-size: 32px;
}

.welcome-text {
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.sub-text {
  color: #5c6b7c;
  font-size: 16px;
  margin: 0;
  line-height: 1.6;
}

.main-content {
  margin-bottom: 20px;
}

.visit-history {
  height: 600px;
  overflow-y: auto;
}

.visit-item {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s ease;
}

.visit-item:hover {
  background: #f8f9fa;
}

.visit-item.active {
  background: #e6f7ff;
  border-right: 3px solid #1890ff;
}

.visit-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.visit-date {
  color: #1890ff;
  font-weight: 500;
}

.visit-department {
  color: #606266;
}

.visit-doctor {
  color: #606266;
  margin-bottom: 8px;
}

.visit-diagnosis {
  color: #303133;
  font-weight: 500;
}

.follow-up-card {
  min-height: 600px;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
}

.empty-tip p {
  margin-top: 16px;
  font-size: 14px;
}

.medication-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.medication-item {
  margin-bottom: 16px;
}

.med-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.med-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.med-details {
  color: #606266;
}

.med-details p {
  margin: 8px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.advice-content {
  padding: 16px 0;
}

.advice-list {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.advice-item {
  margin-bottom: 16px;
}

.advice-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.advice-detail {
  color: #606266;
  line-height: 1.6;
}

@media (max-width: 768px) {
  .after-care-container {
    padding: 16px;
  }

  .main-content {
    margin-bottom: 16px;
  }

  .medication-list,
  .advice-list {
    grid-template-columns: 1fr;
  }
}
</style> 